package com.example.bank.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.bank.domain.Result;
import com.example.bank.pojo.Client;
import com.example.bank.pojo.ClientQuery;
import com.example.bank.pojo.User;
import com.example.bank.service.client.ClientService;
import com.example.bank.service.image.ImageService;
import com.example.bank.service.union.UnionService;
import com.example.bank.service.user.UserService;
import com.example.bank.util.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @author ：Leeziqiang
 * @description：Client控制器类
 * @date ：2021/12/4 14:49
 */
@RestController
@RequestMapping("client")
public class ClientController {

    private static final Logger logger = LoggerFactory.getLogger(ClientController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private UnionService unionService;
    @Autowired
    private ImageService imageService;

    // 业务员业务员添加一个客户
    @PostMapping("/add")
    @RequiresRoles("业务员")
    public Result addClient(@Validated Client client, BindingResult bindingResult) {
        logger.info("--------------添加一个客户------------");
        // 校验数据合法性
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
        }
        // 获取业务员id
        String id = JWTUtil.obtainId();
        // 添加一个客户
        client = clientService.addClient(client);
        // 将该客户与业务员绑定
        if (ObjectUtil.isNull(client)) {
            logger.info("----------业务员{}添加客户失败----------", userService.findUserName(id));
            return ResultUtil.error("添加失败");
        }
        if (unionService.bind(id, client.getClientId())) {
            logger.info("ClientController---addClient----业务员{}添加客户成功----------", userService.findUserName(id));
            return ResultUtil.success("添加成功");
        }
        logger.info("----------业务员{}添加客户失败----------", userService.findUserName(id));
        return ResultUtil.error("添加失败");
    }

    // 业务员查看自己的客户(所有状态)
    @PostMapping("/show")
    @RequiresRoles(logical = Logical.OR, value = {"经理", "业务员"})
    public Result showClient() {
        // 获取用户id
        String id = JWTUtil.obtainId();
        // 获取对应的客户id
        List<String> clientIds = unionService.getClientIds(id);
        // 获取客户列表
        if (ObjectUtil.isEmpty(clientIds)) {
            return ResultUtil.success("目前无客户");
        }
        List<Client> clients = clientService.listClients(clientIds);
        clients.removeIf(client -> client.getApprovalState().equals(5));
        logger.info("ClientController---showClient---业务员{}成功查看相应客户----------", userService.findUserName(id));
        return ResultUtil.success(clients);
    }

    // 查看特定审批状态的客户
    @PostMapping("/list")
    @RequiresRoles(logical = Logical.OR, value = {"经理", "业务员"})
    public Result listClient(Integer approvalState) {
        String id = JWTUtil.obtainId();
        List<String> clientIds = unionService.getClientIds(id);
        if (ObjectUtil.isEmpty(clientIds)) {
            return ResultUtil.success("目前无客户");
        }
        List<Client> clients = clientService.listClients(clientIds, approvalState);
        logger.info("ClientController---listClient---成功查看特定状态的客户");
        return ResultUtil.success(clients);
    }

    // 查看单个客户
    @PostMapping("/check")
    @RequiresRoles(logical = Logical.OR, value = {"经理", "业务员", "业务员管理员", "admin"})
    public Result checkClient(String clientId) throws Exception{
        if (StrUtil.isEmpty(clientId)) {
            return ResultUtil.error("参数错误");
        }
        Client client = clientService.findById(clientId);
        if (ObjectUtil.isNull(client)) {
            return ResultUtil.success(null);
        }
        // 查询图片
//        String clientIdNumber = clientService.findNumberById(clientId);
        Map<String, List<String>> images = imageService.listImages(clientId);
        client.setImages(images);
        logger.info("ClientController---checkController---成功查看单个客户信息");
        return ResultUtil.success(client);
    }

    @PostMapping("/obtainId")
    public Result obtainId() {
        String id = UUID.randomUUID().toString();
        return ResultUtil.success("success",id);
    }

    // 业务员上传
    @PostMapping("/upload")
    @RequiresRoles(logical = Logical.OR, value = {"业务员", "业务员管理员", "admin"})
    public Result upload(HttpServletRequest request) throws Exception {
        String type = request.getParameter("type");
        String clientIdNumber = request.getParameter("clientIdNumber");
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        // 对应前端的upload的name参数“file”
        MultipartFile multipartFile = req.getFile("file");
        // realPath填写电脑文件路径
        String realPath = "/www/wwwroot/bank_resources/upload/";
        // 取得图片的格式后缀
        String originalLastName = multipartFile.getOriginalFilename();
        String picLastName = originalLastName.substring(originalLastName.lastIndexOf("."));
        String picName = clientIdNumber + ":" + type + picLastName;
        try {
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(realPath, picName);
            // 如果同名文件存在，删除同名文件
            if (file.exists()) {
                String path = "http://120.55.91.16:8081/pic/" + picName;
                imageService.deleteByPath(path);
                file.delete();
            }
            multipartFile.transferTo(file);
            logger.info("---------图片添加成功------------");
            // 将图片路径存入数据库
            type = type.substring(0, type.length() - 1);
            String dbPath = "http://120.55.91.16:8081/pic/" + picName;
            String dbName = "bank_resources/upload/" + picName;
            imageService.addImage(clientIdNumber, dbName, dbPath, type);
            return ResultUtil.success("上传成功");
        } catch (IOException e) {
            logger.info(e.getMessage());
            return ResultUtil.error(e.getMessage());
        } catch (IllegalStateException e) {
            logger.info(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }


    // 业务员、经理更改客户审批状态
    @PostMapping("/update")
    @RequiresRoles(logical = Logical.OR, value = {"经理", "业务员"})
    public Result updateState(String clientId, Integer state) {
        if (StrUtil.isEmpty(clientId) || ObjectUtil.isNull(state)) {
            return ResultUtil.error("参数错误");
        }
        if (clientService.updateClientState(clientId, state)) {
            logger.info("ClientController---updateState---成功更改客户审批状态");
            return ResultUtil.success("更改成功");
        }
        return ResultUtil.error("更改失败");
    }

    // 经理上传截止时间
    @PostMapping("/deadline")
    @RequiresRoles("经理")
    public Result deadline(String clientId, String deadline, Integer state) {
        if (StrUtil.isEmpty(clientId) || ObjectUtil.isNull(state) || ObjectUtil.isEmpty(deadline)) {
            return ResultUtil.error("参数错误");
        }
        if (clientService.updateDeadline(clientId, deadline, state)) {
            logger.info("Controller---deadline---成功上传截止时间");
            return ResultUtil.success("更改成功");
        }
        return ResultUtil.error("更改失败");
    }

    // 管理员
    @PostMapping("/query")
    @RequiresRoles("admin")
    public Result query(ClientQuery clientQuery) {
        List<Client> clients = clientService.listByClientQuery(clientQuery, null);
        if (ObjectUtil.isNull(clients)) {
            return ResultUtil.error("查询失败");
        }
        return ResultUtil.success(clients);
    }

    // 总管理员查询所有的业务员
    @PostMapping("/listSalesman1")
    public Result listSalesman1() {
        List<User> salesmen = userService.listSalesman();
        return ResultUtil.success(salesmen);
    }

    // 业务员管理员查询所有的业务员
    @PostMapping("/listSalesman2")
    public Result listSalesman2() {
        String id = JWTUtil.obtainId();
        List<User> salesmen = userService.listSalesman2(id);
        return ResultUtil.success(salesmen);
    }

    @PostMapping("/query2")
    @RequiresRoles("业务员管理员")
    public Result query2(ClientQuery clientQuery) {
        String id = JWTUtil.obtainId();
        List<String> clientIds = unionService.getClientIds(id);
        if (ObjectUtil.isEmpty(clientIds)) {
            return ResultUtil.success("目前无客户");
        }
        List<Client> clients = clientService.listByClientQuery(clientQuery, clientIds);
        if (ObjectUtil.isNull(clients)) {
            return ResultUtil.error("查询失败");
        }
        return ResultUtil.success(clients);
    }

    // 业务管理员修改订单
    @PostMapping("/updateClient")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "业务员管理员", "业务员"})
    public Result update(Client client) {
        if (clientService.updateClient(client)) {
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.error("修改失败");
    }

    // 业务管理员删除订单
    @PostMapping("/delete")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "业务员管理员","业务员"})
    public Result delete(String clientId) {
        if (clientService.deleteClient(clientId)) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.error("删除失败");
    }

    // 删除照片
    @PostMapping("/deleteImage")
    @RequiresRoles(logical = Logical.OR, value = {"admin", "业务员管理员", "业务员"})
    public Result deleteImage(String imagePath) {
        if (imageService.deleteByPath(imagePath)) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.error("删除失败");
    }



}
